<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
      <el-row class="category_opration">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            :options="categoryList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="categoryChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="showAddAttrDialog"
          >添加参数</el-button>

          <el-table :data="dynamicAttributeList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attrVals"
                  :key="i"
                  closable
                  @close="handleDelVals(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attrName"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeAttribute(scope.$index,scope.row,dynamicAttributeList)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="showAddAttrDialog"
          >添加属性</el-button>
          <el-table :data="staticAttributeList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attrVals"
                  :key="i"
                  closable
                  @close="handleDelVals(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attrName"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeAttribute(scope.$index,scope.row,staticAttributeList)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form ref="attrFormRef" :model="attrForm" :rules="attrFormRules">
        <el-form-item :label="titleText" prop="attrName" label-width="100px">
          <el-input v-model="attrForm.attrName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addAttrDialog">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form ref="editAttrFormRef" :model="editAttrForm" :rules="editAttrFormRules">
        <el-form-item :label="titleText" prop="attrName" label-width="100px">
          <el-input v-model="editAttrForm.attrName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editAttrDialog()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCategoryList()
  },
  data() {
    return {
      categoryList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'catId',
        label: 'catName',
        children: 'children'
      },
      selectedKeys: [],
      activeName: 'many',
      addDialogVisible: false,
      editDialogVisible: false,
      attrForm: {
        attrName: '',
        attrSel: ''
      },
      attrFormRules: {
        attrName: [
          { required: true, message: '参数名称不能为空', trigger: 'blur' }
        ]
      },
      editAttrForm: {
        attrName: ''
      },
      editAttrFormRules: {
        attrName: [
          { required: true, message: '参数名称不能为空', trigger: 'blur' }
        ]
      },
      dynamicAttributeList: [],
      staticAttributeList: [],
      attribute: {}
    }
  },
  methods: {
    async getCategoryList() {
      const { data: result } = await this.$http.get('/categories')
      if (result.status !== 200) {
        return this.$message.error('获取分类数据失败！')
      }

      this.categoryList = result.data
    },
    async getAttributeList() {
      const { data: result } = await this.$http.get(`/categories/${this.categoryId}/attributes`, { params: { attrSel: this.activeName } })
      if (result.status === 200) {
        if (result.data) {
          result.data.forEach(item => {
            item.attrVals = item.attrVals ? item.attrVals.split(' ') : []
            item.inputVisible = false
            item.inputValue = ''
          })
        }
        if (this.activeName === 'many') {
          this.dynamicAttributeList = result.data
        } else {
          this.staticAttributeList = result.data
        }
      }
    },
    categoryChange() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.dynamicAttributeList = []
        this.staticAttributeList = []
        return null
      }

      this.getAttributeList()
    },
    handleTabClick(tab, event) {
      this.getAttributeList()
    },
    showAddAttrDialog() {
      this.addDialogVisible = true
    },
    showEditDialog(row) {
      this.attribute = row
      this.editAttrForm.attrName = row.attrName
      this.editDialogVisible = true
    },
    removeAttribute(index, row, rows) {
      this.$confirm('此操作将永久删除改参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: result } = await this.$http.delete(`/attributes/${row.id}`)
        if (result.status === 200) {
          rows.splice(index, 1)
          this.$message.success('删除成功！')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    addAttrDialog() {
      this.$refs.attrFormRef.validate(async valid => {
        if (valid) {
          this.attrForm.attrSel = this.activeName
          const { data: result } = await this.$http.post(`/categories/${this.categoryId}/attributes`, this.attrForm)
          if (result.status === 200) {
            this.$message.success('添加参数成功！')
            this.addDialogVisible = false
            this.getAttributeList()
          }
        }
      })
    },
    editAttrDialog() {
      this.$refs.editAttrFormRef.validate(async valid => {
        if (valid) {
          const { data: result } = await this.$http.put(`/attributes/${this.attribute.id}`, this.editAttrForm)
          if (result.status === 200) {
            this.$message.success('添加参数成功！')
            this.editDialogVisible = false
            this.attribute.attrName = this.editAttrForm.attrName
            // this.getAttributeList()
          }
        }
      })
    },
    addDialogClosed() {
      this.$refs.attrFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editAttrFormRef.resetFields()
    },
    async saveAttrVals(row) {
      // 添加参数值
      const { data: result } = await this.$http.put(`/attributes/${row.id}`, { attrVals: row.attrVals.join(' ') })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }

      this.$message.success('修改参数项成功！')
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return null
      }

      // 保存参数项
      row.attrVals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    handleDelVals(index, row) {
      row.attrVals.splice(index, 1)
      this.saveAttrVals(row)
    },
    showInput(row) {
      row.inputVisible = true

      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    isDisabled() {
      return this.selectedKeys.length !== 3
    },
    categoryId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style scoped lang="less">
.category_opration {
  margin: 15px 0;
  .el-cascader {
    width: 270px;
  }
}
.el-table {
  margin-top: 15px;
}
.input-new-tag {
  width: 120px;
}
.el-tag {
  margin: 0 10px 0 0;
}
</style>
